import ChildrenPageUtils from '@/store/extends'
import { uSelectDevStatus, selectDevFunBydDevId } from './../../../api/setting'
import { observable, computed, action } from 'mobx'
import { createContext } from 'react'
import deepClone from '@/utils/deepClone'

// const excludeFuns = ['0149', '0001', '0003']
const excludeFuns = ['0001', '0003']

class Access extends ChildrenPageUtils {
  @observable pageQuery: { isManage: '是' | '否'; devId: string } = {
    isManage: '否',
    devId: ''
  }

  @observable accessData: Setting.AccessData = {
    devName: '',
    standRatio: 0,
    standRatioStatus: '',
    nowDevStatus: '',
    totalCheckHour: 0,
    exceptionCount: 0,
    onLineRatio: 0,
    standRatioTimeRatio: 0,
    devFunList: []
  }

  @observable defaultAccessData: Setting.AccessData = {
    devName: '',
    standRatio: 0,
    standRatioStatus: '',
    nowDevStatus: '',
    totalCheckHour: 0,
    exceptionCount: 0,
    onLineRatio: 0,
    standRatioTimeRatio: 0,
    devFunList: []
  }

  /**从devFunList中排除不需要的功能 */
  @computed get devFunListFilter() {
    return this.accessData.devFunList.filter(
      item => !excludeFuns.includes(item.devFunCode)
    )
  }

  /**从devFunList中筛选出被排除掉的功能 */
  @computed get devFunListExclude() {
    let obj: { [key: string]: Setting.DevFun } = {}
    let filter = this.accessData.devFunList.filter(item => {
      return excludeFuns.includes(item.devFunCode)
    })
    console.log(filter)
    for (let i = 0; i < filter.length; i++) {
      const fun = filter[i]
      obj[fun.devFunCode] = fun
    }
    return Object.keys(obj).length ? obj : null
  }

  @action.bound
  async updatePageDataSource(target?: string) {
    if (!this.pageQuery.devId) return
    let res1 = await uSelectDevStatus({ devId: this.pageQuery.devId })
    if (res1 && res1.result === 'success') {
      let res2 = await selectDevFunBydDevId({ devId: this.pageQuery.devId })
      // console.log(res2);
      // res2.data.push({
      //   devFunCode: "8854",
      //   devFunDesc: "功能控制2",
      //   devFunId: 8854,
      //   devFunName: "功能控制2",
      //   devFunValue: null,
      //   devGId: "LHTest_000000009",
      //   devId: 1683,
      //   status: "1"
      // })

      if (res2 && res2.result === 'success') {
        this.accessData = { ...res1.data, devFunList: res2.data }
      } else {
        this.accessData = deepClone(this.defaultAccessData)
      }
    } else {
      this.accessData = deepClone(this.defaultAccessData)
    }
  }

  @action.bound
  clearPage() {
    this.accessData = {
      devName: '',
      standRatio: 0,
      standRatioStatus: '',
      nowDevStatus: '',
      totalCheckHour: 0,
      exceptionCount: 0,
      onLineRatio: 0,
      standRatioTimeRatio: 0,
      devFunList: []
    }
  }
}
export const accessStore = createContext(new Access())
